package org.example.demo7.controller;

import jakarta.annotation.Resource;
import org.example.demo7.entity.Book;
import org.example.demo7.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
public class BookController {
    @Resource
    private BookService bookService;

    @ResponseBody
    @GetMapping("/setValue")
    public String setValue(){
        bookService.setValue("redis","Spring Data Redis");
        return "保存键-值对成功!";
    }

    @ResponseBody
    @GetMapping("/getValue")
    public String getValue(){
        return bookService.getValue("redis");
    }

    @ResponseBody
    @GetMapping("/saveBook")
    public String saveBook(){
        Book book = new Book(1,"C语言",50.0,"计算机",100,"101.jpg","","张三",50);
        bookService.saveBook(book);
        return "保存一本书成功!";
    }

    @GetMapping("/findBook")
    public String findBook(Model model){
        Book book = bookService.findBookById(1);
        model.addAttribute("book",book);
        return "book";
    }

    @GetMapping("/saveBooks")
    @ResponseBody
    public String saveBooks(){
        Book book1 = new Book(1,"C语言",50.0,"计算机",100,"101.jpg","","张三",50);
        Book book2 = new Book(2,"java",80.0,"计算机",100,"101.jpg","","张三",50);
        Book book3 = new Book(3,"mysql",90.0,"计算机",100,"101.jpg","","张三",50);
        List<Book> books = new ArrayList<Book>();
        books.add(book1);
        books.add(book2);
        books.add(book3);
        bookService.savaBooks("101",books);
        return "保存多本书成功!";
    }

    @GetMapping("/findBookById")
    public String findBookById(int id,Model model){
        List<Book> books = bookService.findBooks("101");
        Book book = new Book();
        if (books!=null&&books.size()>0) {
            book=books.get(id-1);
        }
        model.addAttribute("book",book);
        return "book";
    }

    @GetMapping("/findBooks")
    public String findBooks(Model model){
        List<Book> book = bookService.findBooks("101");
        model.addAttribute("book",book);
        return "books";
    }

    @GetMapping("/deleteBook")
    public String deleteBook(int id,Model model){
        List<Book> books = bookService.findBooks("101");
        books.remove(id-1);
        bookService.savaBooks("101",books);
        List<Book> books1 = bookService.findBooks("101");
        model.addAttribute("book",books1);
        return "books";
    }
}
